﻿using AutoMapper;
using B.S.AuthCenter.Api.Read.Application.Command.MenuRole;
using B.S.AuthCenter.Api.Read.DTOs;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;

namespace B.S.AuthCenter.Api.Read.Application.Handler.MenuRole
{
    public class GetMenuTreeHandler : IRequestHandler<GetMenuTreeCommand, ApiResult<List<MenuParentDTO>>>
    {
        IBaseRepository<MenuManageModel> menuREpo;
        IMapper mapper;

        public GetMenuTreeHandler(IBaseRepository<MenuManageModel> menuREpo, IMapper mapper)
        {
            this.menuREpo = menuREpo;
            this.mapper = mapper;
        }

        public Task<ApiResult<List<MenuParentDTO>>> Handle(GetMenuTreeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<MenuParentDTO>> res=new ApiResult<List<MenuParentDTO>>();
            res.Datas = GetTreeMenu(0);
            res.Msg = "查询树形菜单成功";
            res.Code = ApiEnum.Success;
            return Task.FromResult(res);
        }
        public List<MenuParentDTO> GetTreeMenu(int Pid)
        {
            var tree=menuREpo.GetAll().Where(c=>c.Pid==Pid && !c.IsDeleted).ToList();
            var model=mapper.Map<List<MenuParentDTO>>(tree);
            foreach (var item in model)
            {
                item.children=GetTreeMenu(item.Id);
            }
            return model;
        }
    }
}
